var api = require('../../../config/api.js');
var util = require('../../../utils/util.js');
var app = getApp();
var that;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    jumpPage: '',
    needJump: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    if (options.page) {
      that.setData({
        jumpPage: decodeURIComponent(options.page),
        needJump: true,
      });
    }
  },
  checkLogin() {
    util.login().then((res) => {
      util.toast.loading("自动登录中...");
      app.postPureForm(api.CheckLogin, { code: res.code, isAllow: true }).then(rsp => {
        //wx.clearStorage(); //清除缓存
        let res = rsp.data;
        //是否授权基本信息(微信头像，昵称)
        if (res.isAuthBaseInfo) {
          app.globalData.isAuthBaseInfo = true;
          app.globalData.userInfo = res.userInfo;
          wx.setStorageSync('userInfo', res.userInfo);
          wx.setStorageSync('isAuthBaseInfo', true);
        } else {
          wx.setStorageSync('isAuthBaseInfo', false);
        }
        //实名是否认证成功
        app.globalData.isCert = res.isCert;
        wx.setStorageSync('isCert', res.isCert);

        wx.setStorageSync('isTouristRent', res.isTouristRent);
        app.isTouristRent = res.isTouristRent;
        wx.setStorageSync('phoneNumber', res.phoneNumber);
        wx.setStorageSync('tenantNo', res.tenantNo);
        wx.setStorageSync('token', res.token);
        app.globalData.phoneNumber = res.phoneNumber;
        app.globalData.tenantNo = res.tenantNo;
        app.globalData.hasLogin = true;
        console.log('go into index...');
        if (that.data.needJump && that.data.jumpPage.indexOf('pages/index/index') == -1) {
          wx.redirectTo({
            url: '/' + that.data.jumpPage,
          })
        } else {
          var p = getCurrentPages()[0];
          if (!p.data.isUpdate) {
            p.setData({ isUpdate: true });
          }
          wx.switchTab({
            url: '/pages/index/index',
          })
        }
      }).catch((err) => {
        console.log("检测登录", err);
        that.refreshCode();
      });
    }).catch((err) => {
      console.log("未登录报异常：", err);
      that.refreshCode();
    });
  },
  refreshCode: function () {
    util.login().then((res) => {
      var p = encodeURIComponent(that.data.jumpPage);
      wx.navigateTo({
        url: '/pages/login/login?page=' + p,
      })
    }).catch((err) => {
      console.log("未登录报异常：", err);
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //检测是否有使用过
    that.checkLogin();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})